<?php

namespace Admin\Controller;

use User\Api\UserApi;
use Org\Util\Sync;

/**
 * 秒杀控制器
 * @author zhangwei
 * 2015-06-22
 */
class SeckillController extends AdminController {

    /**
     * 秒杀活动列表
     * @author zhangwei
     * 2015-06-22
     */
    public function index() {
        $title = I('title');
        $sql = "select a.* from gr_seckill a where a.status >= 0 and a.name like '%" . $title . "%'";
        $model = new \Think\Model();
        $list = $model->query($sql);
        int_to_string($list);

        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }

    /**
     * 秒杀商品列表
     * @author zhangwei
     * 2015-06-22
     */
    public function proindex() {
        $title = I('title');
        $sql = "select a.*,b.name sname,b.begindate bdate,b.enddate edate from "
                . "gr_seckill_relation a ,gr_seckill b where a.status = 1 and b.status = 1 and a.skid = b.id group by a.skid";
        $model = new \Think\Model();
        $list = $model->query($sql);
        int_to_string($list);

        $this->assign('_list', $list);
        $this->meta_title = '数据列表';
        $this->display();
    }

    /**
     * 新增秒杀
     * @author zhangwei
     * 2015-06-22
     */
    public function add($gpName = "", $begindate = "", $enddate = "") {
        if (IS_POST) {
            $data = array('name' => $gpName, 'begindate' => strtotime($begindate), 'enddate' => strtotime($enddate),
                'createdate' => NOW_TIME, 'lastupdate' => NOW_TIME);
            $id = M('seckill')->add($data);
            if (!$id) {
                $this->error("添加失败！");
            } else {
                $this->success('添加成功！', U('index'));
            }
        } else {
            $this->display();
        }
    }

    /**
     * 新增秒杀商品
     * @author zhangwei
     * 2015-06-22
     */
    public function proadd() {
        if (IS_POST) {
            $seckillId = I('seckillId');
            $specid_array = I('specid');
            $price_array = I('price');
            $store_array = I('store');
            $maxcnt_array = I('maxcnt');

            $product = M('product');
            $productSpec = M('product_spec');
            $seckill = M('seckill');
            
            for ($i = 0; $i < count($specid_array); $i++) {
                if ($specid_array[$i] == "0" || $price_array[$i] == "") {
                    $this->error("关联商品内容不能为空");
                }
            }

            for ($i = 0; $i < count($specid_array); $i++) {
                $proprice = $productSpec->where(array('id'=>split(",",$specid_array[$i])[0]))->getField('grprice');
                $proimg = $product->where(array('id'=>split(",",$specid_array[$i])[1]))->getField('picurlarray');
                $proname = $product->where(array('id'=>split(",",$specid_array[$i])[1]))->getField('name');
                
                $dataList[] = array('skid' => $seckillId, 'specid' => split(",",$specid_array[$i])[0], 'pid' => split(",",$specid_array[$i])[1],
                    'price' => $price_array[$i], 'inventory' => $store_array[$i], 'maxCnt' => $maxcnt_array[$i], 'proprice'=>$proprice,'proimg'=>$proimg,
                    'createdate' => NOW_TIME, 'lastupdate' => NOW_TIME,'proname'=>$proname);
            }
            
            D('seckill_relation')->addAll($dataList);
            
            
            $products = json_encode(M('seckill_relation')->where(array('skid'=>$seckillId,'status'=>1))->select());
            $prodata = array('products'=>$products,'syncStatus'=>1);
            $seckill->where(array('id'=>$seckillId))->save($prodata);
            
            $this->success('商品添加成功！', U('proindex'));
        } else {
            $sql = "select * from gr_seckill "
                    . "where gr_seckill.status = 1 "
                    . "and not exists (select 1 from gr_seckill_relation seck where gr_seckill.id = seck.skid and seck.status = 1) "
                    . "order by createdate desc";
            
            $model = new \Think\Model();
            $list = $model->query($sql);
            $data['list'] = $list;

            $sql1 = "select pro.name pname,pro.id pid,prospc.id specid,prospc.name specname "
                    . "from gr_product pro, gr_product_spec prospc "
                    . "where pro.id = prospc.pid "
                    . "and pro.status = 1 "
                    . "and prospc.status = 1 "
                    . "order by pname,specid desc";
                    
            $model1 = new \Think\Model();
            $prolist = $model1->query($sql1);
            $data['prolist'] = $prolist;

            $this->data = $data;
            $this->display();
        }
    }

    /**
     * 编辑秒杀
     * @author zhangwei
     * 2015-06-22
     */
    public function edit($gpName = "", $begindate = "", $enddate = "") {
        $id = I('id');
        if (IS_POST) {

            $syncStatus = M('seckill')->where(array('id' => $id))->getField('syncStatus');
            if ($syncStatus == 0) {
                $syncStatus = 2;
            } else {
                $syncStatus = 1;
            }

            $data = array('name' => $gpName, 'begindate' => strtotime($begindate),
                'enddate' => strtotime($enddate), 'lastupdate' => NOW_TIME, 'syncStatus' => $syncStatus);

            if (!M('seckill')->where(array('id' => $id))->save($data)) {
                $this->error("修改失败！");
            } else {
                $this->success('修改成功！', U('index'));
            }
        } else {
            $data = M('seckill')->where(array('id' => $id))->find();
            $this->data = $data;
            $this->display();
        }
    }

    /**
     * 秒杀商品修改
     * @author zhangwei
     * 2015-06-22
     */
    public function proedit($specid = "", $price = "", $store = "", $maxcnt = "") {
        $id = I('id');
        
        if (IS_POST) {
            $product = M('product');
            $productSpec = M('product_spec');
            $seckill = M('seckill');
            
            $specid_array = I('specid');
            $store_array = I('store');
            $maxcnt_array = I('maxcnt');
            $price_array = I('price');
            $skid = $_REQUEST['skid'];
            
            $syncStatus = M('seckill')->where(array('id' => $skid))->getField('syncStatus');
            if ($syncStatus == 0) {
                $syncStatus = 2;
            } else {
                $syncStatus = 1;
            }

            if ($specid_array) {
                for ($i = 0; $i < count($specid_array); $i++) {
                    if ($specid_array[$i] == "0" || $price_array[$i] == "") {
                        $this->error("商品内容不能为空");
                    }
                }
            }

            if ($specid_array) {
                for ($i = 0; $i < count($specid_array); $i++) {
                    $proprice = $productSpec->where(array('id'=>split(",",$specid_array[$i])[0]))->getField('grprice');
                    $proimg = $product->where(array('id'=>split(",",$specid_array[$i])[1]))->getField('picurlarray');
                    $proname = $product->where(array('id'=>split(",",$specid_array[$i])[1]))->getField('name');
                    
                    $dataList[] = array('skid' => $skid, 'specid' => split(",",$specid_array[$i])[0], 
                        'pid' => split(",",$specid_array[$i])[1],'price' => $price_array[$i],
                        'inventory' => $store_array[$i], 'maxCnt' => $maxcnt_array[$i], 'createdate' => NOW_TIME, 
                        'lastupdate' => NOW_TIME,'proprice'=>$proprice,'proimg'=>$proimg,'proname'=>$proname);
                }
                D('seckill_relation')->addAll($dataList);
                
                $products = json_encode(M('seckill_relation')->where(array('skid'=>$skid,'status'=>1))->select());
                $prodata = array('products'=>$products,'syncStatus'=>$syncStatus);
                $seckill->where(array('id'=>$skid))->save($prodata);
            }
            $this->success('修改成功！', U('proindex'));
        } else {
            $sid = I('sid');
            //$data['seckpro'] = M('seckill_relation')->where(array('skid' => $sid,'status'=>1))->select();
            $data['secklist'] = M('seckill')->where('status=1')->order('createdate desc')->select();
            $data['seck'] = M('seckill')->where(array('id' => $sid))->find();

            $sql = "select pro.name pname,pro.id pid,prospc.id specid,prospc.name specname "
                    . "from gr_product pro, gr_product_spec prospc "
                    . "where pro.id = prospc.pid "
                    . "and pro.status = 1 "
                    . "and prospc.status = 1 "
                    . "and not exists (select 1 from gr_seckill_relation seck where prospc.id = seck.specid "
                    . "and seck.status = 1 "
                    . "and seck.skid = ".$sid.") "
                    . "order by pname,specid desc";
            
            $model = new \Think\Model();
            $prolist = $model->query($sql);
            $data['prolist'] = $prolist;

            $sql1 = "select pro.name pname,prospc.name specname,seckpro.* from gr_product pro, gr_product_spec prospc,gr_seckill_relation"
                    . " seckpro where pro.id = prospc.pid and seckpro.specid = prospc.id and seckpro.status =1 and pro.status = 1 and prospc.status = 1"
                    . " and seckpro.skid = " . $sid;
            $model1 = new \Think\Model();
            $seckpro = $model1->query($sql1);
            $data['seckpro'] = $seckpro;

            //dump($data);return;

            $this->assign("skname", $data['seck']['name']);
            $this->assign("skid", $sid);
            $this->data = $data;
            $this->display();
        }
    }

    /**
     * 上推活动
     * @author zhangwei
     * 2015-05-21
     */
//    public function pushSeckill() {
//        $reuslt = D("SeckillLeanCloud")->push();
//        $this->success('活动数据上推成功！', U('index'), true);
//    }
    
    /**
     * 上推活动关联商品
     * @author zhangwei
     * 2015-05-21
     */
//    public function pushSeckillPro() {
//        $reuslt = D("SeckillProLeanCloud")->push();
//        $this->success('活动商品数据上推成功！', U('index'), true);
//    }

    /**
     * 下拉
     * @author zhangwei
     * 2015-05-21
     */
    public function pull() {
        $sync = new Sync();

        $reuslt = $sync->pull("Order");
        $reuslt = $sync->pull("OrderGoods");
        $this->success('订单数据下拉成功！', U('index'), true);
    }

    /**
     * 删除秒杀活动
     * @author zhangwei
     * 2015-06-22
     */
    public function del($id = 0) {
        if ($id) {
            $seckill = M("seckill");
            
            $syncStatus = M('seckill')->where(array('id' => $id))->getField('syncStatus');
            if ($syncStatus != 1) {
                $syncStatus = 3;
            } else {
                $syncStatus = 0;
            }

            $data = array('status' => -1, 'syncStatus' => $syncStatus);
            $result = $seckill->where(array('id' => $id))->save($data);

            if ($result) {
                $this->success('删除成功！', U('index'));
            } else {
                $this->error("删除失败！");
            }
        }
    }

    /**
     * 删除秒杀关联的所有商品
     * @author zhangwei
     * 2015-06-22
     */
    public function prodel($skid = 0) {
        if ($skid) {
            $seckill_relation = M("seckill_relation");
            $seckill = M('seckill');
            
            $data = array('status' => -1,'syncStatus'=>3);
            $result = $seckill_relation->where(array('skid' => $skid))->save($data);

            $products = json_encode($seckill_relation->where(array('skid'=>$skid,'status'=>1))->select());
            $prodata = array('products'=>$products,'syncStatus'=>2);
            $seckill->where(array('id'=>$skid))->save($prodata);
            
            if ($result) {
                $this->success('删除成功！', U('proindex'));
            } else {
                $this->error("删除失败！");
            }
        }
    }

    //删除关联商品
    public function specdelajax($id = "",$skid = "") {

        if ($id == "") {
            $this->error("关联商品刪除失败!");
        }
        
        $syncStatus = M('seckill_relation')->where(array('id' => $id))->getField('syncStatus');
        if ($syncStatus != 1) {
            $syncStatus = 3;
        } else {
            $syncStatus = 0;
        }

        $ProductspecData = array('status' => -1,'syncStatus'=>$syncStatus);
        $Productspec = D('seckill_relation');
        if ($Productspec->where(array('id' => $id))->save($ProductspecData)) {
            
            $seckill = M('seckill');
            
            $products = json_encode(M('seckill_relation')->where(array('skid'=>$skid,'status'=>1))->select());
            $prodata = array('products'=>$products,'syncStatus'=>2);
            $seckill->where(array('id'=>$skid))->save($prodata);
            
            $this->success("关联商品刪除成功!");
        } else {
            $this->error("关联商品刪除失败！");
        }
    }

    //修改关联商品
    public function speceditajax($id = "",$skid = "", $price = "", $store = "", $maxcnt = "") {
        IF ($id == "" || $price == "") {
            $this->error("关联商品修改失败!");
        }

        $syncStatus = M('seckill_relation')->where(array('id' => $id))->getField('syncStatus');
        if ($syncStatus == 0) {
            $syncStatus = 2;
        } else {
            $syncStatus = 1;
        }


        $ProductspecData = array('price' => $price, 'maxCnt' => $maxcnt, 'lastupdate' => NOW_TIME, 'inventory' => $store, 'syncStatus' => $syncStatus);
        $Productspec = D('seckill_relation');
        if ($Productspec->where(array('id' => $id))->save($ProductspecData)) {
            
            $seckill = M('seckill');
            
            $products = json_encode(M('seckill_relation')->where(array('skid'=>$skid,'status'=>1))->select());
            $prodata = array('products'=>$products,'syncStatus'=>2);
            $seckill->where(array('id'=>$skid))->save($prodata);
            
            $this->success("关联商品修改成功!");
        } else {
            $this->error("数据没有发生变化，修改失败！");
        }
    }
    
    
    /**
     * 上推
     * @author wangyuanlin
     * 2015-06-23
     */
    public function push(){
        
        //获取要上推的数据源
        $list = M('seckill')->where(array('syncStatus'=>array('egt', 1)))->select();

        //执行上推操作
        $list = $this->pushParse('Seckill',
            array('objectId'=>'id',
                'name'=>'name',
                'begindate'=>'begindate',
                'enddate'=>'enddate',
                'products'=>'products',
                'status'=>'status',
                'syncStatus'=>'syncStatus'),
            function($src){
                //前调函数
                $microbeg = sprintf("%03d",($src['begindate'] - floor($src['begindate'])) * 1000);
                $src['begindate'] = array("__type"=>"Date","iso"=> date('Y-m-d',$src['begindate']).'T'.date('H:i:s',$src['begindate']).'.'.$microbeg.'Z');
                
                $microend = sprintf("%03d",($src['enddate'] - floor($src['enddate'])) * 1000);
                $src['enddate'] = array("__type"=>"Date","iso"=> date('Y-m-d',$src['enddate']).'T'.date('H:i:s',$src['enddate']).'.'.$microend.'Z');
                return $src;
            },
            function($src){
                //后调函数
                //数据上推到云端后，更新本地数据的同步状态 （syncStatus ＝ 0）
                M('seckill')->where('id='.$src['objectId'])->data(array('syncStatus'=>0))->save();
                return $src;
            },
            $list);
            
       $this->success('商品分类数据上推成功！', U('index'),true);
    }

}
